<?php
/**
 * 数组常用
 * @author yangdongqi <yangdongqi@hayzone.com>
 * @package lib.helpers.utils
 */
class CArrayUtil {
	
	/**
	 * 填充数组的key
	 * <pre>
	 * $params = array();
	 * $this->fillKeys($params, array('one', 'two', 'three'));
	 * // 运行结果
	 * $params = array(
	 *  'one' => null,
	 *  'two' => null,
	 *  'three' => null,
	 * );
	 * 
	 * $params = array('one' => 'new');
	 * $this->fillKeys($params, array('one', 'two', 'three'));
	 * // 运行结果
	 * $params = array(
	 *  'one' => 'new',
	 *  'two' => null,
	 *  'three' => null,
	 * );
	 * </pre>
	 * @param 需要填充的数组 $array
	 * @param array $keys 数组的键名(s)
	 * @param mixed $content 填充内容
	 * @param boolean $force 是否强制覆盖存在键值所对应的内容
	 * @return void
	 */
	public function fillKeys(&$array, $keys, $content = null, $force = false) {
		foreach($keys as $k) {
			if($force) {
				$array[$k] = $content;
			} else {
				$array[$k] = isset($array[$k]) ? $array[$k] : $content;
			}
		}
	}
	
	/**
	 * Merges any number of arrays / parameters recursively, replacing 
	 * entries with string keys with values from latter arrays. 
	 * If the entry or the next value to be assigned is an array, then it 
	 * automagically treats both arguments as an array.
	 * Numeric entries are appended, not replaced, but only if they are 
	 * unique
	 *
	 * calling: result = arrayMergeRecursiveDistinct(a1, a2, ... aN)
	 **/
	function arrayMergeRecursiveDistinct() {
		$aArrays = func_get_args();
		$aMerged = $aArrays[0];

		for($i=1; $i<count($aArrays); $i++){
			if(is_array($aArrays[$i])) {
				foreach ($aArrays[$i] as $key => $val) {
					if(is_array($aArrays[$i][$key])) {
						$aMerged[$key] = is_array($aMerged[$key]) 
							? self::arrayMergeRecursiveDistinct($aMerged[$key], $aArrays[$i][$key]) 
							: $aArrays[$i][$key];
					} else {
						$aMerged[$key] = $val;
					}
				}
			}
		}
		return $aMerged;
	}
	
	/**
	 * 合并数组的元素的字符串
	 * @param array $a1
	 * @param array $a2
	 * @param string $seperator
	 * @return array
	 */
	public function arrayStrMerge($a1, $a2, $igList = array(), $seperator = ' ') {
		
		foreach($a2 as $k=>$v) {
			if(in_array($k, $igList)) continue;
			if(isset($a1[$k])) {
				$value = $v.$seperator.$a2[$k];
				$a1[$k] = $value;
			} else {
				$a1[$k] = $a2[$k];
			}
		}
		
		return $a1;
		
	}
	
}

?>